import { api } from "./api";
import { genAppToken } from "../../utils/jwt";
// import { isDev } from "../../config";
import { fillShopName } from "./shop";

// user.status 2-已绑定手机号 3-管理员

export async function getUserInfo(body, userId) {
  const info = await api.getUserInfoBase({
    id: userId,
  });
  if (!info) {
    throw {
      code: 401,
      msg: "用户信息不存在",
    };
  }
  if (info.status == 3) {
    info.admList = await api.getMembers({
      mobile: info.mobile,
      on: 1,
      _order: "role asc",
    });
    if (body.admId) {
      info.adm = info.admList.find((it) => it.id == body.admId);
    }
    if (info.adm) {
      const adm = info.adm;
      if (adm.sid) {
        await fillShopName(adm);
      }
      info.token = genAppToken(info.id, {
        sid: adm.sid,
        role: adm.role,
      });
    }
    if (info.admList.length) {
      await fillShopName(info.admList);
    } else {
      delete info.admList;
      await api.postUserInfo({
        id: userId,
        status: 2,
      });
    }
  }
  return info;
}

export async function postInfo(body, userId) {
  const ban = ["mobile", "openid", "unioinid", "vcode"];
  for (const key in body) {
    if (ban.includes(key)) throw "Invalid Info";
  }
  const info = await api.postUserInfoBase({
    id: userId,
    ...body,
  });
  return info;
}
